import { applyDecorators, UnsupportedMediaTypeException, UseInterceptors } from "@nestjs/common";
import { FileInterceptor, FilesInterceptor } from "@nestjs/platform-express";
import { MulterOptions } from "@nestjs/platform-express/multer/interfaces/multer-options.interface";

// 上传 单文件 装饰器函数
export function upload(fieldName = "file", options: MulterOptions = {}) {
  return applyDecorators(UseInterceptors(FileInterceptor(fieldName, options)));
}

// 上传 多文件 装饰器函数
export function uploads(fieldName = "files", maxCount = 5, options: MulterOptions = {}) {
  return applyDecorators(UseInterceptors(FilesInterceptor(fieldName, maxCount, options)));
}

// 文件 MIME 类型过滤器函数
export function fileMimetypeFilter(mimes: string[]) {
  return (req: any, file: Express.Multer.File, callback: (error: Error | null, acceptFile: boolean) => void) => {
    if (mimes.some(mime => file.mimetype.includes(mime))) {
      callback(null, true);
    } else {
      // 如果文件的 MIME 类型不在列表中，则触发不支持的媒体类型异常
      callback(new UnsupportedMediaTypeException("文件类型错误"), false);
    }
  };
}
